<template>
  <div class="flobal-search">
    <el-select v-model="screen" class="screen" placeholder="请选择跳转类型">
      <el-option label="全部" value=""></el-option>
      <el-option
        v-for="item in dict.link_type"
        :key="item.dataValue"
        :label="item.dataName"
        :value="item.dataValue"
      ></el-option>
    </el-select>
    <el-tooltip
      class="item"
      effect="dark"
      :content="placeholder"
      placement="top-start"
    >
      <KiSelect
        v-model="selfValue"
        class="search-targe"
        :options.sync="sourceList"
        value-key="id"
        :props="{ value: 'id', label: 'name', labelRight: 'typeName' }"
        :search="searchTargetPage"
        :searchImmediately="false"
        :loading="searching"
        :placeholder="placeholder"
      />
    </el-tooltip>
  </div>
</template>

<script>
import { searchAll } from './api'
import { mapGetters } from 'vuex'

export default {
  name: 'GlobalSearch',
  props: ['value', 'link_type', 'type', 'sourceId', 'sourceName'],
  data () {
    return {
      selfValue: null,
      searching: false,
      sourceList: [],
      screen: '',
      placeholder: '请输入搜索内容'
    }
  },
  computed: {
    ...mapGetters(['dict']),
    srcTypeList () {
      // 如果没传搜索类别的话就搜索全部
      // 2.0需求，暂时不需要从外部接收传入的类型限制，全部做成统一搜索
      // return this.link_type || this.dict.link_type.map((_) => _.dataValue)
      return this.dict.link_type.map(_ => _.dataValue)
    }
  },
  watch: {
    value: {
      immediate: true,
      deep: true,
      handler (newVal, oldVal) {
        this.selfValue = newVal
        if (newVal) {
          // 只有初次打开才需要设置默认值
          if (this.type && this.sourceId && this.sourceName) {
            // 判断传进来的这个值在不在选项列表中，不在的话移除
            if (!this.sourceList.some(_ => _.id == this.sourceId)) {
              this.sourceList.push({
                src_type: this.type,
                id: this.sourceId,
                name: this.sourceName,
                typeName: this.getTypeName(this.type)
              })
            }
          }
        } else {
          this.searchTargetPage()
          this.$forceUpdate()
        }
      }
    },
    type: {
      immediate: true,
      handler (newVal) {
        if (!newVal && this.selfValue) {
          this.$emit('update:type', '00')
        }
      }
    },
    selfValue: {
      immediate: true,
      deep: true,
      handler (newVal, oldVal) {
        this.$emit('change', newVal || undefined)
        this.$emit('input', newVal || undefined)
        let info = this.getInfo(newVal)
        if(!info.src_type && info.id && info.name) {
          info.src_type = '00'
        }
        this.$emit('update:type', info.src_type)
        this.$emit('update:sourceId', info.id)
        this.$emit('update:sourceName', info.name)
      }
    },
    screen (n) {
      // 选择了搜索项时，重新生成placeholder
      this.placeholderCreate()
    }
  },
  created () {
    this.placeholderCreate()
  },
  methods: {
    getTypeName (type) {
      let dictItem = this.dict.link_type.filter(item => item.dataValue == type)
      return dictItem.length > 0 ? dictItem[0].dataName : ''
    },
    getInfo (id) {
      let option = this.sourceList
      for (let i = 0; i < option?.length; i++) {
        if (option[i].id == id) {
          return option[i]
        }
      }
      return {
        type: undefined,
        sourceId: undefined,
        sourceName: undefined
      }
    },
    placeholderCreate () {
      let result = '请输入搜索内容'
      if (this.$attrs.placeholder) {
        result = this.$attrs.placeholder
      } else {
        if (this.dict && this.dict.link_type) {
          result = '搜索 '
          this.dict.link_type.map(v => {
            let srcTypeList = this.screen ? [this.screen] : this.srcTypeList
            if (srcTypeList.includes(v.dataValue)) {
              result += (result === '搜索 ' ? '' : ' | ') + v.dataName
            }
          })
        }
      }
      this.placeholder = result
    },
    searchTargetPage (key) {
      return new Promise((res, rej) => {
        if (key) {
          this.searching = true
          searchAll({
            srcTypeList: this.screen != '' ? [this.screen] : this.srcTypeList,
            key
          })
            .then(
              ({ data }) => {
                let resData =
                  data?.map(v => {
                    //polyfill: 兼容后端没有区分景区和场馆的问题
                    // if (v.src_type === 'scenic' && v.subType === '02') {
                    //   v.typeName = '场馆'
                    //   v.src_type = 'venue'
                    // }
                    return v
                  }) || []
                if (resData.length > 100) {
                  resData.length = 100
                }
                res(resData)
              },
              () => {
                res([])
              }
            )
            .finally(e => {
              this.searching = false
            })
        } else {
          res([])
        }
      })
    }
  }
}
</script>

<style lang="scss">
.flobal-search {
  display: flex;
  .screen {
    width: 130px !important;
    .el-input__inner {
      border-radius: 4px 0 0 4px;
      border-right: none;
    }
  }
  .search-targe {
    flex: 1;
    .el-input__inner {
      border-radius: 0 4px 4px 0;
    }
  }
}
</style>
